//
//  igViewController.m
//  ScanBarCodes
//
//  Created by Torrey Betts on 10/10/13.
//  Copyright (c) 2013 Infragistics. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "igViewController.h"
#import "dao.h"

@interface igViewController () <AVCaptureMetadataOutputObjectsDelegate>
{
    AVCaptureSession *_session;
    AVCaptureDevice *_device;
    AVCaptureDeviceInput *_input;
    AVCaptureMetadataOutput *_output;
    AVCaptureVideoPreviewLayer *_prevLayer;
    
    UIView *_highlightView;
    UILabel *_label;
    
    UIView *leftSearchView;
    UIView *rigthSearchView;
}
@end

@implementation igViewController

NSTimer *timerSearchBarcode;

- (IBAction)backtoHome:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    UITabBarController *tab = [mainStoryBoard instantiateViewControllerWithIdentifier:@"TabBarView"];
    [tab setSelectedIndex:0];
    
    [self presentViewController:tab animated:YES completion:nil];
}

- (IBAction)callNumber:(id)sender {

    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (void)hideTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds);
                         tabBar.frame = tabFrame;
                         content.frame = window.bounds;
                     }];
}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    // saving an NSString
    [prefs setObject:@"LoadHomeFirst" forKey:@"keyToLookupString"];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self hideTabBar];
    
//-----------------------------------------------------------
//Retorno desde la bùsqueda de productos.
    dao *objDAO = [[dao alloc] init];
    
    int intProductBack = 0;
    
    intProductBack = [objDAO obtainProductBack];
    
    if (intProductBack == 0) {

        [objDAO insertProductBack:1];
    }else{
        [objDAO updateProductBack:1];
    }
//------------------------------------------------------------
    _highlightView = [[UIView alloc] init];
    _highlightView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
    _highlightView.layer.borderColor = [UIColor greenColor].CGColor;
    _highlightView.layer.borderWidth = 3;
    
    //  [_highlightView addSubview: [[UIImageView alloc]  initWithImage:[UIImage imageNamed:@"1.png"] ] ];
    
    [self.view addSubview:_highlightView];
    
    _label = [[UILabel alloc] init];
    _label.frame = CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40);
    _label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    _label.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65];
    _label.textColor = [UIColor whiteColor];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.text = @"[Fije el lente en la zona a escanear]";
    [self.view addSubview:_label];
    
    _session = [[AVCaptureSession alloc] init];
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    
    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
    if (_input) {
        [_session addInput:_input];
    } else {
        NSLog(@"Error: %@", error);
    }
    
    _output = [[AVCaptureMetadataOutput alloc] init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [_session addOutput:_output];
    
    _output.metadataObjectTypes = [_output availableMetadataObjectTypes];
    
    _prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];

    _prevLayer.frame = self.view.bounds;
//  _prevLayer.frame = CGRectMake(0, 60, 320, 420);
    
    _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:_prevLayer];
    
    [_session startRunning];
    
    //-----------------------------------------------------------------
    
    leftSearchView = [[UIView alloc] init];
    [leftSearchView addSubview:[[UIImageView alloc]  initWithImage:[UIImage imageNamed:@"mira_lente_izquierdo.png"] ] ];

    rigthSearchView = [[UIView alloc] init];
    [rigthSearchView addSubview:[[UIImageView alloc]  initWithImage:[UIImage imageNamed:@"mira_lente_derecho.png"] ] ];
    
    //--------------------
    //Observación: Ajustamos la mira del lente mas arriba.
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
        leftSearchView.frame = CGRectMake(20, 50, 77, 320);
        rigthSearchView.frame = CGRectMake(225, 50, 77, 320);
    }
    else if(result.height == 568)
    {
        leftSearchView.frame = CGRectMake(20, 110, 77, 320);
        rigthSearchView.frame = CGRectMake(225, 110, 77, 320);
    }
    //--------------------
    
    [self.view addSubview:leftSearchView];
    [self.view addSubview:rigthSearchView];
    
    [self.view bringSubviewToFront:_highlightView];
    [self.view bringSubviewToFront:_label];
    
    [self.view bringSubviewToFront:leftSearchView];
    [self.view bringSubviewToFront:rigthSearchView];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view. // e.g. self.myOutlet = nil;
    
    [timerSearchBarcode invalidate];
    timerSearchBarcode = nil;
}

- (void) gotoSearch{

    [timerSearchBarcode invalidate];
    timerSearchBarcode = nil;
    
  [self performSegueWithIdentifier:@"segueBarCode" sender:nil];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    CGRect highlightViewRect = CGRectZero;
    AVMetadataMachineReadableCodeObject *barCodeObject;
    NSString *detectionString = nil;
    NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
                              AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
                              AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];

    bool boolExitSearch = NO;
    
    for (AVMetadataObject *metadata in metadataObjects) {
        for (NSString *type in barCodeTypes) {
            if ([metadata.type isEqualToString:type])
            {
                barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
                highlightViewRect = barCodeObject.bounds;
                detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
                break;
            }
        }
        
        if (detectionString != nil)
        {
            _label.text = detectionString;
            boolExitSearch = YES;
             break;
        }
        else
            _label.text = @"[Fije el lente en la zona a escanear]";
    }
    
    _highlightView.frame = highlightViewRect;

    if (boolExitSearch) {
        [_session stopRunning];
        
        timerSearchBarcode = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(gotoSearch) userInfo:nil repeats:YES];
    }

}


@end






